package com.newproject.resmi;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity{
	private Handler handler;
	private ProgressDialog loginProgressDialog = null;
	private static final String USER_DETAILS = "UserPrefs";
	
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.login);
    	handler = new Handler();
    	   	
        Button launch = (Button)findViewById(R.id.login_button);        
        
        launch.setOnClickListener( new OnClickListener() {        	
        	public void onClick(View viewParam) {
        		EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
                EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
                
                InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(passwordEditText.getWindowToken(), 0); // dismiss keyboard
        		
                String sUserName = usernameEditText.getText().toString();
                String sPassword = passwordEditText.getText().toString();
        		
                if(sUserName.trim().length() == 0 || sPassword.trim().length() == 0){
                	AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
                	builder.setMessage(Login.this.getString(R.string.enterlogin))
                	       .setCancelable(true)
		                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                        public void onClick(DialogInterface dialog, int id) {
		                             dialog.cancel();
		                        }
		                    });
                	AlertDialog alert = builder.create();
                	alert.show();
                } else {
                	ValidateLogin vl = new ValidateLogin(sUserName, sPassword);
            		new Thread(vl).start();                   
                	loginProgressDialog = ProgressDialog.show(Login.this,   
                			Login.this.getString(R.string.wait),  Login.this.getString(R.string.checking), true);
                }               
        	}
        });        
    }
	
	@Override
	public void onResume() {
		super.onResume();		
		//check if a user is already logged in
		SharedPreferences settings = getSharedPreferences(USER_DETAILS, Context.MODE_PRIVATE);
		String clientId = settings.getString("clientId", "0");
		boolean defaultPass = settings.getBoolean("defaultPass", false);
		Intent myIntent;
		if(defaultPass) {
			myIntent = new Intent(Login.this, ChangePassword.class);
			Login.this.startActivity(myIntent);
	    	Login.this.finish();
		} else if (!clientId.equals("0")) {
			myIntent = new Intent(Login.this, TabView.class);
			Login.this.startActivity(myIntent);
	    	Login.this.finish();
		}
		
		if (getRememberLoginPref()){
			String userName = settings.getString("userName", "");
			if (!userName.equals("")) {
				EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
				usernameEditText.setText(userName);
			}
		}
	}
	
	private class ValidateLogin implements Runnable{
		private String login;
		private String password;
		public ValidateLogin(String login, String password){
			this.login = login;
			this.password = password;
		}
		public String getPassword() {
			return this.password;
		}
		public void run() {
			//final String clientId = DataManager.validateMobileLogin(this.login, Integer.toString(this.password.hashCode()));
			final String clientId = DataManager.validateDirectLogin(this.login, this.password);
			
			SharedPreferences settings = getSharedPreferences(USER_DETAILS, Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("userName", this.login);
		    editor.commit();
			
			handler.post(new Runnable() {
				public void run() {
					loginProgressDialog.dismiss();				
					//String test = clientId;					
					if (isOnline()) {						
						String msg;
						if (clientId.equals("") || clientId.equals("0")){						
							if (clientId == ""){
								msg = getString(R.string.connection_failed);
							} else {
								msg = getString(R.string.wrong_user);
							}
							AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
		                	builder.setMessage(msg)
		                	       .setCancelable(true)
				                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				                        public void onClick(DialogInterface dialog, int id) {
				                             dialog.cancel();
				                        }
				                    });
		                	AlertDialog alert = builder.create();
		                	alert.show();
						} else {
							getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);							
									
							// put clientId in shared prefs, so all activities can see it
							SharedPreferences settings = getSharedPreferences(USER_DETAILS, Context.MODE_PRIVATE);							
							SharedPreferences.Editor editor = settings.edit();
						    editor.putString("clientId", clientId);
						    editor.commit();
						    
						    if (getPassword().equals("123")) {	
						    	editor.putBoolean("defaultPass", true);
							    editor.commit();
							    
						    	Intent myIntent = new Intent(Login.this, ChangePassword.class);
						    	//Bundle myBundle = new Bundle();
						    	//myBundle.putBoolean("defaultPass", true);
						    	//myIntent.putExtras(myBundle);						    	
				    	    	Login.this.startActivity(myIntent);
				    	    	Login.this.finish();
						    } else {   	
							    Intent myIntent = new Intent(Login.this, TabView.class);
				    	    	Login.this.startActivity(myIntent);
				    	    	Login.this.finish();
						    }
						}
					} else {
						AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
			    		builder.setMessage(getString(R.string.no_connection))
			    		       .setCancelable(false)
			    		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			    		           public void onClick(DialogInterface dialog, int id) {
			    		                Login.this.finish();
			    		           }
			    		       });
			    		AlertDialog alert = builder.create();
			    		alert.show();
					}					
				}
			});	
			
		}
	}
	
	/**
	 * Check if a device is connected to a network
	 */
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null) {
			return cm.getActiveNetworkInfo().isConnectedOrConnecting();
		}		
		return false;
	}
	
	private boolean getRememberLoginPref() { 
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		return prefs.getBoolean("prefRememberLogin", false);
	}
}
